<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import { User, SwitchButton } from '@element-plus/icons-vue'

const userStore = useUserStore()
const router = useRouter()

// 在组件挂载时获取用户信息
onMounted(async () => {
  if (localStorage.getItem('token')) {
    try {
      await userStore.fetchUserInfo()
    } catch (error) {
      console.error('Error fetching user info:', error)
    }
  }
})

const logout = async () => {
  await userStore.logout()
  router.push('/login')
}
</script>

<template>
  <div class="nav-container">
    <el-menu
      class="nav-menu"
      mode="horizontal"
      :router="true"
      :ellipsis="false"
    >
      <div class="left-menu">
        <el-menu-item index="/qa">问答</el-menu-item>
        <el-menu-item index="/wrong-questions">备忘录</el-menu-item>
        <el-menu-item index="/community">社区</el-menu-item>
      </div>

      <div class="right-menu">
        <el-dropdown class="user-dropdown">
          <span class="user-profile">
            <el-avatar 
              :size="32" 
              :src="userStore.userInfo?.avatar"
              :icon="User"
            />
            <span class="username">{{ userStore.userInfo?.username }}</span>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item divided @click="logout">
                <el-icon><SwitchButton /></el-icon>退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-menu>
  </div>
</template>

<style scoped>
.nav-container {
  border-bottom: solid 1px var(--el-menu-border-color);
}

.nav-menu {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.left-menu {
  display: flex;
}

.right-menu {
  display: flex;
  align-items: center;
}

.user-dropdown {
  height: 60px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
}

.username {
  font-size: 14px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-menu--horizontal) {
  border-bottom: none;
}
</style> 